//
//  XJTagSuperMarketViewController.m
//  XinJiangMall
//
//  Created by RaoBo on 2018/6/25.
//  Copyright © 2018年 Tzyang. All rights reserved.
//

#import "XJTagSuperMarketViewController.h"

#import "XJTagSmAllCategoryViewController.h"

//Model
#import "XJTagSMBigCtyModel.h" //大类model
//view
#import "RBTitleButton.h"
#import "XJRequestFailView.h" //网络错误view



@interface XJTagSuperMarketViewController () <UIScrollViewDelegate>

/**大类数据源*/
@property (nonatomic, strong) NSMutableArray *bigCtyArray;

//标题veiw
@property(nonatomic, strong) UIScrollView *titleScrollView;
/**1.标记选中的按钮*/
@property(nonatomic, strong) RBTitleButton *selectedBtn;
/**2.黄线*/
@property (nonatomic, strong) UIView *yellowLine;
/**3.装 RBTitleButton */
@property (nonatomic, strong) NSMutableArray *titleBtnArray;



/**大scrollView*/
@property (nonatomic, strong) UIScrollView *bigScrollView;

@property (nonatomic, strong) XJRequestFailView * failView;
@end

@implementation XJTagSuperMarketViewController

#pragma mark - 一 lazy
- (NSMutableArray *)bigCtyArray {
    if (!_bigCtyArray) {
        _bigCtyArray = [NSMutableArray array];
    }
    return _bigCtyArray;
}

- (NSMutableArray *)titleBtnArray {
    if (!_titleBtnArray) {
        _titleBtnArray = [NSMutableArray array];
    }
    return _titleBtnArray;
}

- (UIView *)yellowLine {
    if (!_yellowLine) {
        _yellowLine = [UIView new];
        _yellowLine.backgroundColor = XJCOLOR_RGB(255, 168, 67);
    }
    return _yellowLine;
}


- (XJRequestFailView *)failView {
    if (!_failView) {
        _failView = [[XJRequestFailView alloc] initWithFrame:self.view.bounds];
        
        XJWeakSelf(self);
        _failView.retryBtnBlock = ^{
            [weakself requestBigCategory];
        };
    }
    return _failView;
}

#pragma mark - 二 生命周期

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setupNavAndBackgroundColor];
    
    [self requestBigCategory];
    
    
    self.failView.hidden = YES; //默认hidden = YES.请求失败显示
    [self.view addSubview:self.failView];
}

- (void)setupNavAndBackgroundColor {
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = @"超市商场";
}



#pragma mark - 三 网络请求

//多个网络请求使用信号量来做。

//- (void)
//请求大类数据
- (void)requestBigCategory {
    
    [XJHttpTool requestHomeTagSupermarketWithGoodsCategoryId:self.goods_category_id successH:^(id responseObjc) {
        
        NSString *code = [NSString stringWithFormat:@"%@",responseObjc[@"code"]];
        if ([code isEqualToString:@"0"]) {
            NSDictionary *dataDic = responseObjc[@"data"];
            
            //导航栏标题
            self.navTitle = dataDic[@"home_goods_category"][@"name"];
            
            // 大类moel
            NSArray *category_list = dataDic[@"category_list"];
            for (NSDictionary *ctyDic in category_list) {
                XJTagSMBigCtyModel *bigM = [XJTagSMBigCtyModel mj_objectWithKeyValues:ctyDic];
                [self.bigCtyArray addObject:bigM];
            }
            
            
            dispatch_async(dispatch_get_main_queue(), ^{
            
                [self rb_setupTitleViewWithArray:self.bigCtyArray];
                [self rb_addChildVCWithArray:self.bigCtyArray];
                [self rb_addChildVCViews];
                
                self.failView.hidden = YES; //默认hidden = YES.请求失败显示
                
            });
            
        }else {
            [JRToast showWithText:responseObjc[@"message"]];
            self.failView.hidden = NO; //默认hidden = YES.请求失败显示
        }
        
    } failH:^(NSError *error) {
        XJLog(@"%@",error);
    }];
}

#pragma mark - 四 网易效果
//创建标题按钮
- (void)rb_setupTitleViewWithArray:(NSArray *)arr {
    self.titleScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, KWidth, 40)];
    [self.view addSubview:self.titleScrollView];
    
    if (arr.count == 0) {
        return;
    }
    
    //设置contenSize
    self.titleScrollView.contentSize = CGSizeMake(KWidth * arr.count, 0);
    
    
    CGFloat btn_w = 100;
    CGFloat btn_h = self.titleScrollView.rb_height;
    
    //添加按钮
    for (int i=0 ; i<arr.count; i++) {
        XJTagSMBigCtyModel *bigM = arr[i];
        
        RBTitleButton *button = [RBTitleButton buttonWithType:(UIButtonTypeCustom)];
        button.tag = i; //添加tag值
        [button setTitle:bigM.name forState:(UIControlStateNormal)];
        button.frame = CGRectMake(btn_w*i, 0, btn_w, btn_h);
        [self.titleScrollView addSubview:button];

        [button addTarget:self action:@selector(clicktTitleBtnAction:) forControlEvents:(UIControlEventTouchUpInside)];
        
        //转入数组中方便后便用
        [self.titleBtnArray addObject:button];
    }
    
    
    RBTitleButton *firstButton = [self.titleBtnArray firstObject];
    
    //添加线
    CGFloat line_h = self.titleScrollView.rb_height;
    
    self.yellowLine.frame = CGRectMake(0, line_h - 5, 40, 2);
    self.yellowLine.rb_center_x = firstButton.rb_center_x;
    
    [self.titleScrollView addSubview:self.yellowLine];
}

- (void)clicktTitleBtnAction:(RBTitleButton *)button {
    XJLog(@"%@",button.titleLabel.text);
    
    //切换按钮选中状态
    self.selectedBtn.selected = NO;
    button.selected = YES;
    self.selectedBtn = button;
    
    [UIView animateWithDuration:0.25 animations:^{
        self.yellowLine.rb_center_x = button.rb_center_x;
    }];
    
    
    // 让scrollView滚动到对应的位置
//    CGPoint offset = self.scrollView.contentOffset;
//    offset.x  = btn.tag * _scrollView.rb_width;
//    [self.scrollView setContentOffset:offset animated:YES];
    
    CGPoint offset = self.bigScrollView.contentOffset;
    offset.x = button.tag * self.bigScrollView.rb_width;
    [self.bigScrollView setContentOffset:offset animated:YES];
}


//添加子视图控制器
- (void)rb_addChildVCWithArray:(NSArray *)arr {
    if (arr.count == 0) {
        return;
    }
    
    for (int i=0; i<arr.count; i++) {
        
        XJTagSMBigCtyModel *bigModel = self.bigCtyArray[i];
        
        XJTagSmAllCategoryViewController *allctyVC = [[XJTagSmAllCategoryViewController alloc] init];
        
        allctyVC.category_id = bigModel.categoryId;
        [self addChildViewController:allctyVC];
    }
    
    
    //子视图控制器添加完成之后在初始化 bigSrollview(它放在self.view上,子视图控制器的view添加在他上面)
    [self rb_setupBigScrollView];
}


// 初始化bigScrollVeiw 子控制器的view都添加在他上面
//这个方法一定要在添加子视图控制完成之后调用。
- (void)rb_setupBigScrollView {
    self.bigScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 40, KWidth, KHeight - 40)];
    
    //子视图控制器的个数
    NSInteger count = self.childViewControllers.count;
    XJLog(@"子视图控制器的个数:%ld",count);
    
    self.bigScrollView.contentSize = CGSizeMake(KWidth * count, 0);
    self.bigScrollView.delegate = self;
    self.bigScrollView.pagingEnabled = YES;
    
    [self.view addSubview:self.bigScrollView];
}

//添加子视图控制器的view
- (void)rb_addChildVCViews{
    
    NSInteger index = self.bigScrollView.contentOffset.x / self.bigScrollView.rb_width;
    
    XJLog(@"下标:%ld",index);
    
    if (self.childViewControllers.count == 0) {
        return;
    }
    
    XJTagSuperMarketViewController *chilVC = self.childViewControllers[index];
    if ([chilVC isViewLoaded]) {
        return; //避免重复添加
    }
    
    chilVC.view.frame = self.bigScrollView.bounds;
    [self.bigScrollView addSubview:chilVC.view];
}
    
#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    [self rb_addChildVCViews];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSInteger index = self.bigScrollView.contentOffset.x / self.bigScrollView.rb_width;
    //切换按钮状态
    RBTitleButton *button = self.titleBtnArray[index];
    [self clicktTitleBtnAction:button];
    
    
    //这一行代码有点多余了。
    //切换view
//    [self rb_addChildViews];
}

@end
